package cn.wangkai.peanut.util;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.wangkai.peanut.action.util.LoginCheckAction;
import cn.wangkai.peanut.bean.auth.LoginUser;
import cn.wangkai.peanut.commons.beanutils.BigDecimalConverter;
import cn.wangkai.peanut.commons.beanutils.DateConverter;
import cn.wangkai.peanut.commons.beanutils.SetConverter;
import cn.wangkai.peanut.commons.beanutils.TimestampConverter;
import cn.wangkai.peanut.mvc.admin.model.Unit;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@SuppressWarnings("deprecation")
public class RequestContext {
	private final static Log log = LogFactory.getLog(RequestContext.class);

	private final static ThreadLocal<RequestContext> contexts = new ThreadLocal<RequestContext>();

	private final static String UTF_8 = "UTF-8";
	private static String webroot = null;

	private ServletContext context;
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Object> cookies;
	private static Configuration cfg;
	private static Configuration wycfg;
//	//用户
	private LoginUser user;
	
	public Unit getDepartment(){
		return user==null?null:user.getDepartment();
	}

	public Unit getUnit(){
		return user==null?null:user.getUnit();
	}

	public LoginUser getUser() {
		return user;
	}
	
	private final static String getWebrootPath() {
		String root = RequestContext.class.getResource("/").getFile();
		try {
			root = new File(root).getParentFile().getParentFile().getPath();
//			root += File.separator;
		} catch (Exception e) {
//			throw new RuntimeException(e);
		}
		return root;
	}

	/**
	 * 初始化请求上下文
	 * 
	 * @param ctx
	 * @param req
	 * @param res
	 */
	public static RequestContext begin(ServletContext ctx,
			HttpServletRequest req, HttpServletResponse res) {
		RequestContext rc = new RequestContext();
//		IUserDao userdao = new UserDaoImp();
		rc.context = ctx;
		rc.request = _AutoEncodingRequest(req);
		rc.response = res;
		rc.session = req.getSession(false);
		rc.cookies = new HashMap<String,Object>();
		Cookie[] cookies = req.getCookies();
		if (cookies != null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie ck = cookies[i];
//				log.(ck);
				rc.cookies.put(ck.getName(), ck);
			}
		}
		contexts.set(rc);
		try{
			rc.user =rc.session.getAttribute(LoginCheckAction.USERSESSIONID)==null?null:(LoginUser)rc.session.getAttribute(LoginCheckAction.USERSESSIONID);
		}catch (Exception e) {
			rc.user = null;
		}
		return rc;
	}

	
	public String ip(){
		return request.getRemoteHost();
	}

	public Locale locale() {
		return request.getLocale();
	}

	public void closeCache() {
		header("Pragma", "No-cache");
		header("Cache-Control", "no-cache");
		header("Expires", 0L);
	}

	public String param(String name) {
		return paramString(name, null);
	}
	public String param(String name,List<FileItem> items) {
		return paramString(name, null,items);
	}
	public String paramString(String name, String def_value) {
		String v = request.getParameter(name);
		return (v != null) ? v : def_value;
	}
	public String paramString(String name, String def_value,List<FileItem> items) {
		if(items!=null&&items.size()>0){
			for (FileItem item : items) {
				if(name.equalsIgnoreCase(item.getFieldName())){
					try {
						String v = item.getString("UTF-8");
						return (v != null) ? v : def_value;
					} catch (UnsupportedEncodingException e) {
						return def_value;
					}
				}
			}
		}else{
			String v = request.getParameter(name);
			return (v != null) ? v : def_value;
		}
		return def_value;
	}
	
	public String[] params(String name) {
		return request.getParameterValues(name);
	}

	public String[] params(String name,List<FileItem> items) {
		List<String> lists = new ArrayList<String>();
		for (FileItem item : items) {
			if(name.equalsIgnoreCase(item.getFieldName())){
				try {
					lists.add(item.getString("UTF-8"));
				} catch (UnsupportedEncodingException e) {
				}
			}
		}
		String[] str = new String[lists.size()];
		return lists.toArray(str);
	}
	
	public Long[] paramLongs(String name) {
		String[] strs = params(name);
		Long[] longs = new Long[strs.length];
		for (int i = 0; i < strs.length; i++) {
			longs[i]=NumberUtils.toLong(strs[i]);
		}
		return longs;
	}
	
	public Long paramLong(String name) {
		String v = param(name);
		return (StringUtils.isBlank(v))?null:new Long(v);
	}

	public Long paramLong(String name, Long def_value) {
		String v = param(name);
		return (StringUtils.isBlank(v))?def_value:NumberUtils.toLong(v);
	}
	public Long paramLong(String name,List<FileItem> items) {
		return paramLong(name, null,items);
	}	
	public Long paramLong(String name, Long def_value,List<FileItem> items) {
		String v = param(name,items);
		return (StringUtils.isBlank(v))?def_value:NumberUtils.toLong(v);
	}

	public BigDecimal paramBigDecimal(String name) {
		String v = param(name);
		return (StringUtils.isBlank(v))?null:new BigDecimal(v);
	}

	public BigDecimal paramBigDecimal(String name, BigDecimal def_value) {
		String v = param(name);
		return (StringUtils.isBlank(v))?def_value:new BigDecimal(v);
	}
	public BigDecimal paramBigDecimal(String name, List<FileItem> items) {
		return paramBigDecimal(name, null, items);
	}
	
	public BigDecimal paramBigDecimal(String name, BigDecimal def_value,List<FileItem> items) {
		String v = param(name,items);
		try{
			return (StringUtils.isBlank(v))?def_value:new BigDecimal(v);
		}catch(Exception e){
			return null;
		}
	}
	
	public Boolean paramBoolean(String name) {
		String v = param(name);
		if(StringUtils.isBlank(v))
			return null;
		else{
			if("0".equals(v)) return false;
			else if("1".equals(v)) return true;
			else return BooleanUtils.toBoolean(v);
		}
	}
	
	public Boolean paramBoolean(String name, Boolean def_value) {
		String v = param(name);
		if(StringUtils.isBlank(v))
			return def_value;
		else{
			if("0".equals(v)) return false;
			else if("1".equals(v)) return true;
			else return BooleanUtils.toBoolean(v);
		}
	}
	public Boolean paramBoolean(String name,List<FileItem> items) {
		return paramBoolean(name,null,items);
	}
	public Boolean paramBoolean(String name, Boolean def_value,List<FileItem> items) {
		String v = param(name,items);
		if(StringUtils.isBlank(v))
			return def_value;
		else{
			if("0".equals(v)) return false;
			else if("1".equals(v)) return true;
			else return BooleanUtils.toBoolean(v);
		}
	}
	
	public Integer paramInt(String name) {
		String v = param(name);
		if(v==null||v.equalsIgnoreCase("")) return null;
		return NumberUtils.toInt(v);
	}
	public Integer paramInt(String name, List<FileItem> items){
		return paramInt(name,null,items);
	}
	public Integer paramInt(String name, Integer def_value, List<FileItem> items){
		String v = param(name,items);
		return StringUtils.isBlank(v)?def_value:new Integer(v);
	}
	
	public Integer paramInt(String name, Integer def_value) {
		String v = param(name);
		return StringUtils.isBlank(v)?def_value:new Integer(v);
	}

	public Integer[] paramInts(String name) {
		String[] strs = params(name);
		Integer[] Integers = new Integer[strs.length];
		for (int i = 0; i < strs.length; i++) {
			Integers[i]=NumberUtils.toInt(strs[i]);
		}
		return Integers;
	}
	
	public java.util.Date paramDate(String name) {
		String v = param(name);
		if(v==null||v.equalsIgnoreCase("")) return null;
		return DbTools.StrToDate(v);
	}
	public Date paramsqlDate(String name) {
		String v = param(name);
		if(v==null||v.equalsIgnoreCase("")) return null;
		return DbTools.strtoSqlDate(v);
	}
	
	public byte param(String name, Byte def_value) {
		if(def_value==null)
			return (byte) NumberUtils.toInt(param(name));
		else
			return (byte) NumberUtils.toInt(param(name), def_value);
	}

	public long[] lparams(String name) {
		String[] values = params(name);
		if (values == null)
			return null;
		return (long[]) ConvertUtils.convert(values, long.class);
	}


	public String uri() {
		return request.getRequestURI();
	}

	public String contextPath() {
		return request.getContextPath();
	}
//    
//	public String geturl(){
//		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/ftpGetImg.do?path=";
//	}
	
	public void redirect(String uri) throws IOException {
		response.sendRedirect(uri);
	}


//	public Object getBeanSpring(String beanid){
//		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
//		return factory.getBean(beanid);
//	}
//	
	public void include(String uri) throws ServletException, IOException {
		RequestDispatcher rd = context.getRequestDispatcher(uri);
		rd.include(request, response);
	}

	/**
	 * 返回Web应用的路径
	 * 
	 * @return
	 */
	public static String root() {
		return webroot;
	}

	/**
	 * 获取当前请求的上下文
	 * 
	 * @return
	 */
	public static RequestContext get() {
		return (RequestContext) contexts.get();
	}

	public void end() {
		this.context = null;
		this.request = null;
		this.response = null;
		this.session = null;
		this.cookies = null;
		this.user = null;
//		this.contexts = null;
	}

	/**
	 * 自动编码处理
	 * 
	 * @param req
	 * @return
	 */
	private static HttpServletRequest _AutoEncodingRequest(HttpServletRequest req) {
		 if(req instanceof RequestProxy)
		 return req;
		HttpServletRequest auto_encoding_req = req;
		if ("POST".equalsIgnoreCase(req.getMethod())) {
			try {
				auto_encoding_req.setCharacterEncoding(UTF_8);
			} catch (UnsupportedEncodingException e) {
			}
		}
		 else auto_encoding_req = new RequestProxy(req, UTF_8);
		return auto_encoding_req;
	}

	/**
	 * 输出信息到浏览器
	 * 
	 * @param msg
	 * @throws IOException
	 */
	public void print(Object msg) throws IOException {
		response.getWriter().print(msg);
	}

	public void output_json(String[] key, Object[] value) throws IOException {
		StringBuffer json = new StringBuffer("{");
		for (int i = 0; i < key.length; i++) {
			if (i > 0)
				json.append(',');
			boolean isNum = value[i] instanceof Number;
			json.append("\"");
			json.append(key[i]);
			json.append("\":");
			if (!isNum)
				json.append("\"");
			json.append(value[i]);
			if (!isNum)
				json.append("\"");
		}
		json.append("}");
		print(json.toString());
	}

	public void output_json(String key, Object value) throws IOException {
		output_json(new String[] { key }, new Object[] { value });
	}

	public void error(int code) throws IOException {
		response.sendError(code);
	}

	public void error(int code, String msg) throws IOException {
		error(code, new String[] { msg });
	}

	public void error(int code, String[] msg) throws IOException {
		if (msg.length > 0)
			response.sendError(code, msg[0]);
		else
			response.sendError(code);
	}

	public void forbidden() throws IOException {
		error(HttpServletResponse.SC_FORBIDDEN);
	}

	public void not_found() throws IOException {
		error(HttpServletResponse.SC_NOT_FOUND);
	}

	public ServletContext context() {
		return context;
	}

	public HttpSession session() {
		return session(true);
	}

	public HttpSession session(boolean create) {
		return (session == null && create) ? (session = request.getSession()): session;
	}

	public Object sessionAttr(String attr) {
		HttpSession ssn = session();
		return (ssn != null) ? ssn.getAttribute(attr) : null;
	}
	
	public void session(String attr,Object obj) {
		if(obj!=null&&attr!=null) session.setAttribute(attr, obj);
	}
	

	public HttpServletRequest request() {
		return request;
	}

	public HttpServletResponse response() {
		return response;
	}

	public Cookie cookie(String name) {
		return (Cookie) cookies.get(name);
	}

	public String header(String name) {
		return request.getHeader(name);
	}

	public void header(String name, String value) {
		response.setHeader(name, value);
	}

	public void header(String name, int value) {
		response.setIntHeader(name, value);
	}

	public void header(String name, long value) {
		response.setDateHeader(name, value);
	}

	/**
	 * 将HTTP请求参数映射到bean对象中
	 * 
	 * @param req
	 * @param beanClass
	 * @return
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws Exception
	 */
	public Object form(Object bean) throws IllegalAccessException,InvocationTargetException {
	    ConvertUtils.register(new DateConverter(), Date.class);
	    ConvertUtils.register(new DateConverter(), java.sql.Date.class);
	    ConvertUtils.register(new TimestampConverter(), Timestamp.class);
	    ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class);
	    ConvertUtils.register(new SetConverter(), Set.class);
		BeanUtils.populate(bean, request.getParameterMap());
		return bean;
	}

	/**
	 * 
	 * @param parm
	 * @return
	 * @throws JSONException
	 */
	public JSONObject paramjson(String parm){
		String jsonv = request.getParameter(parm);
		if(StringUtils.isBlank(jsonv)) return null;
		return JSONObject.parseObject(jsonv);
	}
	
	public JSONArray paramjsonArray(String parm){
		String jsonv = request.getParameter(parm);
		if(StringUtils.isBlank(jsonv)) return null;
		return JSONArray.parseArray(jsonv);
	}
	/**
	 * 
	 * @param <T>
	 * @param bean
	 * @param parm
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws JSONException
	 * @throws InstantiationException 
	 */
	public <T> T formjson(Class<T> beanclass,String parm) throws IllegalAccessException,InvocationTargetException, InstantiationException {
	    T t = beanclass.newInstance();
		return formjson(t,parm);
	}

	public <T> T formjson(T t,String parm) throws IllegalAccessException,InvocationTargetException, InstantiationException {
		JSONObject json = paramjson(parm);
		Set<String> keys = json.keySet();
		//Iterator<String> keys = json.keys();
		Map<String,Object> mpas = new HashMap<String,Object>();
		for (String k : keys) {
            Object v = json.get(k);
            mpas.put(k, v);
        }
	    ConvertUtils.register(new DateConverter(), Date.class);
	    ConvertUtils.register(new DateConverter(), java.sql.Date.class);
	    ConvertUtils.register(new TimestampConverter(), Timestamp.class);
	    ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class);
	    ConvertUtils.register(new SetConverter(), Set.class);
        BeanUtils.populate(t, mpas);
		return t;
	}

	
	public <T> List<T> formjsonlist(Class<T> beanclass,String parm) throws IllegalAccessException,InvocationTargetException, InstantiationException {
		JSONArray jsonlist = paramjsonArray(parm);
		if(jsonlist==null) return null;
		List<T> lists = new ArrayList<T>();
		for(int i=0;i<jsonlist.size();i++){
			JSONObject json = jsonlist.getJSONObject(i);
			Set<String> keys = json.keySet();
			Map<String,Object> mpas = new HashMap<String,Object>();
			for (String k : keys) {
	            Object v = json.get(k);
	            mpas.put(k, v);
	        }
		    ConvertUtils.register(new DateConverter(), Date.class);
		    ConvertUtils.register(new DateConverter(), java.sql.Date.class);
		    ConvertUtils.register(new TimestampConverter(), Timestamp.class);
		    ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class);
		    ConvertUtils.register(new SetConverter(), Set.class);
		    T t = beanclass.newInstance();
	        BeanUtils.populate(t, mpas);
	        lists.add(t);
		}
		return lists;
	}
	
	/**
	 * 自动解码
	 */
	private static class RequestProxy extends HttpServletRequestWrapper {
		private String uri_encoding; 
		RequestProxy(HttpServletRequest request, String encoding){
			super(request);
			this.uri_encoding = encoding;
		}
		
		/**
		 * 重载getParameter
		 */
		public String getParameter(String paramName) {
			String value = super.getParameter(paramName);
			return _DecodeParamValue(value);
		}

		/**
		 * 重载getParameterMap
		 */
		public Map<String,Object> getParameterMap() {
			@SuppressWarnings("unchecked")
			Map<String,Object> params = super.getParameterMap();
			HashMap<String,Object> new_params = new HashMap<String,Object>();
			Iterator<String> iter = params.keySet().iterator();
			while(iter.hasNext()){
				String key = (String)iter.next();
				Object oValue = params.get(key);
				if(oValue.getClass().isArray()){
					String[] values = (String[])params.get(key);
					String[] new_values = new String[values.length];
					for(int i=0;i<values.length;i++)
						new_values[i] = _DecodeParamValue(values[i]);
					
					new_params.put(key, new_values);
				}
				else{
					String value = (String)params.get(key);
					String new_value = _DecodeParamValue(value);
					if(new_value!=null)
						new_params.put(key,new_value);
				}
			}
			return new_params;
		}

		/**
		 * 重载getParameterValues
		 */
		public String[] getParameterValues(String arg0) {
			String[] values = super.getParameterValues(arg0);
			for(int i=0;values!=null&&i<values.length;i++)
				values[i] = _DecodeParamValue(values[i]);
			return values;
		}

		/**
		 * 参数转码
		 * @param value
		 * @return
		 */
		private String _DecodeParamValue(String value){
			if (StringUtils.isBlank(value) || StringUtils.isBlank(uri_encoding)
					|| StringUtils.isNumeric(value))
				return value;		
			try{
				return new String(value.getBytes("8859_1"), uri_encoding);
			}catch(Exception e){}
			return value;
		}

	}


	public void setAttribute(String name, Object obj) {
		if(name==null) return;
		request.setAttribute(name, obj);
	}
	
	public Object getAttribute(String name) {
		return request.getAttribute(name);
	}
	
	public boolean isparam(String parm){
		return isparam(parm, null);
	}
	
	public boolean isparam(String parm,List<FileItem> items){
		if(items!=null&&items.size()>0){
			for (FileItem item : items) {
				if(parm.equalsIgnoreCase(item.getFieldName())) return true;
			}
		}else{
			@SuppressWarnings("unchecked")
			Enumeration<String> pNames = request.getParameterNames();
			while(pNames.hasMoreElements()){
				 String name=pNames.nextElement();
				 if(StringUtils.equalsIgnoreCase(parm, name)){
					 return true;
				 }
			}
		}
		return false;
	}
	
	public <T> T CopytoBean(T obj){
		return CopytoBean(obj, null);
	}
	
	/**
	 * 拷贝Bean方法
	 * @param obj
	 * @return
	 */
	public <T> T CopytoBean(T obj,List<FileItem> items){
		try{
			PropertyDescriptor[] descriptors =Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
			for (PropertyDescriptor descriptor : descriptors) {
				String proname = descriptor.getName();
				try{
					if(StringUtils.isNotBlank(proname)&&isparam(proname,items)){
						Method writeMethod = descriptor.getWriteMethod();
						if(writeMethod!=null){
							Class<?> type = descriptor.getPropertyType();
							if(StringUtils.isBlank(param(proname, items))){
							}else if(type.isAssignableFrom(Integer.class)){
								writeMethod.invoke(obj, new Object[] { paramInt(proname,items) });
							}else if(type.isAssignableFrom(Boolean.class)){
								writeMethod.invoke(obj, new Object[] { paramBoolean(proname,items) });
							}else if(type.isAssignableFrom(Long.class)){
								writeMethod.invoke(obj, new Object[] { paramLong(proname,items) });
							}else if(type.isAssignableFrom(BigDecimal.class)){
								writeMethod.invoke(obj, new Object[] { paramBigDecimal(proname,items) });
							}else if(type.isAssignableFrom(java.util.Date.class)||type.isAssignableFrom(Date.class)){
								DateConverter converter = new DateConverter();
								writeMethod.invoke(obj, new Object[] {
										//DateUtils.parseDate(param(proname), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd"}) 
										converter.convert(type, param(proname,items))
										});
							}else if(type.isAssignableFrom(Timestamp.class)){
								TimestampConverter converter = new TimestampConverter();
								writeMethod.invoke(obj, new Object[] {
								//		new Timestamp(DateUtils.parseDate(param(proname), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd"}).getTime()) 
										converter.convert(type, param(proname,items))							
								});
							}else {
								writeMethod.invoke(obj, new Object[] { StringUtils.isBlank(param(proname,items))?null:param(proname,items) });
							}
						}
					}
				}catch(Exception e){
					log.debug("转换出现错误"+proname, e);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T[] CopytoBean(T[] t,Class<?> beanClass,List<FileItem> items){
		try{
			for (int i = 0; i < t.length; i++) {
				T obj = t[i];
				if(obj==null) obj = (T) beanClass.newInstance();
				PropertyDescriptor[] descriptors =Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
				for (PropertyDescriptor descriptor : descriptors) {
					String proname = descriptor.getName();
					try{
						if(StringUtils.isNotBlank(proname)){
							String[] vas = params(proname,items);
							System.out.println(vas[i]);
								Method writeMethod = descriptor.getWriteMethod();
								if(writeMethod!=null){
									Class<?> type = descriptor.getPropertyType();
									if(StringUtils.isBlank(vas[i])){
									}else if(type.isAssignableFrom(Integer.class)){
										writeMethod.invoke(obj, new Object[] { NumberUtils.toInt(vas[i]) });
									}else if(type.isAssignableFrom(Boolean.class)){
										writeMethod.invoke(obj, new Object[] { BooleanUtils.toBoolean(vas[i]) });
									}else if(type.isAssignableFrom(Long.class)){
										writeMethod.invoke(obj, new Object[] { NumberUtils.toLong(vas[i]) });
									}else if(type.isAssignableFrom(BigDecimal.class)){
										writeMethod.invoke(obj, new Object[] { new BigDecimal(vas[i]) });
									}else if(type.isAssignableFrom(java.util.Date.class)||type.isAssignableFrom(Date.class)){
										DateConverter converter = new DateConverter();
										writeMethod.invoke(obj, new Object[] {converter.convert(type,vas[i])});
									}else if(type.isAssignableFrom(Timestamp.class)){
										TimestampConverter converter = new TimestampConverter();
										writeMethod.invoke(obj, new Object[] {converter.convert(type,vas[i])});
									}else {
										writeMethod.invoke(obj, new Object[] { vas[i] });
									}
							}
						}
					}catch(Exception e){
						log.debug("转换出现错误"+proname, e);
					}
				}
				t[i] = obj;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}


    public static Template getTemplate(String name)
        throws IOException{
        Template temp = cfg.getTemplate(name, "UTF-8");
        return temp;
    }
	
    public static Template getpageTemplate(String name)
            throws IOException{
    	Template temp = wycfg.getTemplate(name, "UTF-8");
    	return temp;
    }
  
    
	public static void main(String[] args) {
		String url = RequestContext.class.getResource("/").getFile();
		System.out.println(url);
		System.out.println(new File(url+"freemarker.properties").isFile());
		System.out.println(new File(url).getParentFile().getParentFile().getPath());
//        cfg = new Configuration();
//        cfg.setClassForTemplateLoading(RequestContext.class, "/");
//        cfg.setObjectWrapper(new DefaultObjectWrapper());
//		try {
//			Template temp = cfg.getTemplate("vm/as/test.ftl", "UTF-8");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
    static 
    {
    	webroot = getWebrootPath();
    	log.debug("webroot="+webroot);
        cfg = new Configuration();
        cfg.setClassForTemplateLoading(RequestContext.class, "/");
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        wycfg = new Configuration();
        try {
			wycfg.setDirectoryForTemplateLoading(new File(webroot+"/WEB-INF/"));
		} catch (IOException e) {
			log.error(e);
		}
        wycfg.setObjectWrapper(new DefaultObjectWrapper());
        try {
        	Properties p = new Properties(); 
			p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));
			cfg.setSettings(p);
			wycfg.setSettings(p);
		} catch (IOException e1) {
		} catch (TemplateException e) {
		} 

    }
}
